package org.snusmumr.android.media.data;

import org.snusmumr.android.media.Constants;
import org.snusmumr.android.media.data.DatabaseProvider.DatabaseMode;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public abstract class DBOperation<E> {
	private Context context;
	
	public DBOperation(Context context) {
		super();
		this.context = context;
	}
	
	protected DatabaseMode getDatabaseMode() {
		return DatabaseMode.Read;
	}

	public abstract E execute();
	
	public final Context getContext() {
		return context;
	}
	
	protected final DatabaseProvider getDatabaseProvider() {
		return DatabaseProvider.getInstance(context);
	}
	
	protected final Long getFrendId(String androidContactId, String contactName) {
		Long friendId = null;
		SQLiteDatabase database = DatabaseProvider.getInstance(context).getDatabase(DatabaseMode.Write);
		Cursor c = database.query(
				Constants.DB_TABLE_FRIEND, 
				new String[]{FriendColumns._ID}, 
				FriendColumns.ANDROID_CONTACT_ID + "=?" , 
				new String[]{androidContactId.toString()}, 
				null, null, null);
		if(c != null && c.moveToFirst()) {
			friendId = c.getLong(0);
		}
		if(c != null)
			c.close();
		
		if(friendId == null) {
			ContentValues values = new ContentValues();
			values.put(FriendColumns.ANDROID_CONTACT_ID, androidContactId);
			values.put(FriendColumns.DISPLAY_NAME, contactName);
			friendId = database.insert(Constants.DB_TABLE_FRIEND, null, values);
		}
		return friendId;
	}
}
